<?php 
ArrowController::importModel("model.ArrowDataSource");
ArrowController::importModel("controls.presentation.table.columns.ArrowTableStandardColumn");
ArrowController::importModel("controls.common.criteria.IArrowCriteriaUser");  
class ArrowBindCtrl extends ArrowTagContainer implements IArrowCriteriaUser{
	
	protected $dataSource;
	private $suggestField = null;
	private $hiddenField = null;
	private $selectionTable = null;
	private $criteria = null;
	private $separator = ";";
	
	public function configure(){
		
		$this->addProperties(array(
			"fieldName" => false,
			"connectionType" => "single",
			"object" => null,
			"searchFields" => null,
			"value" => null,
			"length" => 10,
			"title" => false,
			"order" => "id",
			"mode" => "advanced", // simple, search, advanced, multiAdvanced, virtual, filter
			"check" => 0,
			"alert" => false,
			"selectedFn" => false,
			"unbindFn" => false,
			"generateHidden" => true,
			"hint" => "",
			"style" => "",
			"namespace" => true,
			"fieldType" => "text",			// textarea
			//TODO do wywalenia
			"legend" => false,
			//TODO do wywalenia
			"emptyLegend" => false
		));
		$this->addRequiredProperties(array( "fieldName", "searchFields"));
		$this->addStateProperties(array());
		//$this->setContentCodeKept(true);
		
	}
	
	public function init(){
		
		$params = array();
		$params["path"] = "/controller::searchService";
		$params["_htmlAmp"] = 0;
		$params["model"] = $this->getProperty("model");
		$params["fields"] = $this->getProperty("searchFields");
		$params["searchCondition"] = $this->getProperty("searchFields");
		$params["length"] = $this->getProperty("length");
		$params["order"] = $this->getProperty("order");
		//Criteria init
		$this->getCriteria();
		if( is_array( $this->criteria ) ) $params["model"] =  $this->criteria[0]->getModel();
		else $params["model"] =  $this->criteria->getModel(); 
		$beanLink = ArrowTemplateLinker::getDefault()->generateBeanLink( $params, true );
		
		$form = $this->getParent("ArrowForm");
		$obj = ($form)?$form:$this;
		
		$hint = $this->getProperty("hint");
		//TODO wycofać
		if(!$hint)
			$hint = $this->getProperty("emptyLegend");
		
		$mode = $this->getProperty("mode");
		$fieldType = ( $this->getProperty("fieldType") == 'text' )?'text':'textarea';
		$this->suggestField = $obj->addNode("form", $fieldType, array("name" => "suggest", "class" => "ctrl-bind-suggest ctrl-bind-suggest-empty", "namespace" => 0, "check" => "0" , "id" => $this->getId()."-suggest", "value" => $hint." ", "style" => $this->getProperty("style") ));
		
		if( $this->getProperty("generateHidden") ) {	
			$this->hiddenField = $obj->addNode("form", "hidden", array(
				"name" => $this->getProperty("fieldName"), 
				"class" => "ctrl-bind-hidden",
				"alert" => $this->getProperty("alert"),
				"check" => $this->getProperty("check"),
				"length" => "1,",
				"value" => $this->getProperty("value"),
				"namespace" => $this->getProperty("namespace")
			));
		}
		
		$jsData = array( 
			"source" => $beanLink,
			"mode" => $mode,
			"selectedFn" => $this->getProperty("selectedFn"),
			"unBindFn" => $this->getProperty("unbindFn"),
			"hint" => $hint
		);
		
		$template = $this->getFirstChild("ArrowCtrlTemplate");
		if( $template )
			$jsData["template"] = $template->getSource();

		$jsData["title"] = $this->getProperty("title");
		
		if( $action =  $this->getFirstChild("ArrowAbstractUIAction")){
			$action->setDisplay(false);
			$jsData["action"] = 1;
		}
		
		
		$this->registerCssFile( "./server/standardModels/org/arrowplatform/controls/bind/resources/ArrowBindCtrl.css" );
		$this->registerJs( get_class($this), dirname(__FILE__)."/resources/ArrowBindCtrl.js", "#ctrl-".$this->getId(), $jsData);
		
		
		
		$this->selectionTable = $this->getFirstChild("ArrowTable");
		
		
		if($this->selectionTable){
			$ajax = $this->addNode("ui","ajax", array("ctrlId" => "ajax-".$this->getId()));

			$this->selectionTable->setParent($ajax);
			
			$this->selectionTable->setProperty("clearCriteria", 0);
			
			$this->selectionTable->setDisplay(false);
			$this->selectionTable->addNode("ui","tablesearch", array("fields" => $this->getProperty("searchFields")));
			
			$aGroup = $this->selectionTable->addNode("ui","actionsGroup", array("name" => "row"));
			$aGroup->addNode("ui", "action", array("name" => "Użyj", "id" => "save", "type" => "html" ))->setContentCode(
				'<div style="display: none;">'.$template->getSource().'</div>'.
				'<a href="{$context.id}" class="ctrl-bind-table-use-close">Wybierz'.(($mode=="multiAdvanced")?' i zamknij':'').'</a>'
			);
			
			if( $mode == 'multiAdvanced' ){
				$aGroup->addNode("ui", "action", array("name" => "Użyj", "id" => "save", "type" => "html" ))->setContentCode(
					'<a href="{$context.id}" class="ctrl-bind-table-use">Dodaj</a>'
				);
			}
			
			$this->selectionTable->init();
		}
		
		
		
	}
	
	public function generateBlockStart(){
		$str='<div class="'.self::CTRL_NAMESPACE.'-bind" id="ctrl-'.$this->getId().'" >';
		$str.= '<div class="ctrl-bind-criteria">'.base64_encode( serialize($this->criteria) ).'</div>';
		
		return $str; 
	}
	public function generateBlockEnd(){
		$res = ArrowController::$activeProject->getResources()->getResource("/graphic/administration/ctrl-more.png");
		$is_hidden = $this->getProperty("generateHidden") ;
		
		$str = "<table><tr><td  class=\"ctrl-bind-simple\"></td>";
		if($this->getProperty("title"))
			$str.= "<td class=\"ctrl-bind-title\">".$this->getProperty("title")."</td>";
		
		$add = "";	
		$label = "";
		$value = '';
		if( $is_hidden )
			$value = $this->hiddenField->getValue();
		if(!empty($value)){
			$tmpCriterias = $this->criteria ; //$this->getCriteria();
			$result = array();
			if( is_array( $tmpCriterias ) ) {
				foreach( $tmpCriterias as $tmpCriteria ) {
					$class = ArrowModel::getModelClass($tmpCriteria->getModel());
					$tmpCriteria->addCondition( "id", explode(";", $value), Criteria::C_IN );
					$result = array_merge( $result, call_user_func(array($class,'getByCriteria'), $tmpCriteria, $class) ) ;
				}
			} else {
				$class = ArrowModel::getModelClass($tmpCriterias->getModel());
				$tmpCriterias->addCondition( "id", explode(";", $value), Criteria::C_IN );
				$result = array_merge( $result, call_user_func(array($class,'getByCriteria'), $tmpCriterias, $class) ) ;
			}
			
			$template = $this->getFirstChild("ArrowCtrlTemplate");
			if( $template ){
				ArrowController::importModel("smarty.SmartyCompiler");
				$compiler = new SmartyCompiler($template->getSource());
			}else
				$compiler = false;
			
			foreach( $result as $row ){
				if($compiler) 
					$label =  $compiler->getResult(array("context" =>$row));
				else
					$label = $row->getObjectName();	
				if( $this->getProperty("mode") == "search" ) $add = "" ;
				else $add.= '<div class="ctrl-bind-item"><a href="'.$row->getPKey().'" class="ctrl-bind-delete-item">&nbsp;</a>'.$label.'</div>';
			}
			
		}
		
		if($this->getProperty("mode") == "search") 
			$this->suggestField->setProperty("value", strip_tags( $label ));
			
		if($this->getProperty("mode") == "filter") { 
			$this->suggestField->setProperty("value", $value);
			$this->suggestField->init();
		}
		
		//echo '<pre>';
		//print_r($this->suggestField->getProperty('value'));
		//exit;
		
		$str.= "<td valign=\"top\">".$this->suggestField->generate()."</td>";
		
		
	
		/*Trzeba było dodać klase bo IE 7 nie rozumie last-child i nie da się inaczej ostylować */
		// TODO tymczasowy if, bo nie działa tabelka
		if($this->getProperty("mode") != "filter") {
			if($this->selectionTable){
				$str.= '<td class="bind-trigger-cell" ><a href="javascript:void(0);" title="Otwórz pełną listę" style="color:black;" class="ctrl-bind-table-trigger" ><img src="'.$res->getRelativePath().'" /></a></td>';

				if( $action = $this->getFirstChild("ArrowAbstractUIAction")){
					$action->setDisplay(false);
					$action->setProperty("name", "");
					$action->init();
					$str.= '<td class="ctrl-bind-action" >'.$action->generate().'</td>';
				}
				
				$str.= '</tr></table>';
				$str.= '<div class="ctrl-bind-table" >'.$this->selectionTable->getParent()->generate().'</div>';
			}else{
				$str.= '</tr></table>';
			}
			$str.= '<div class="ctrl-bind-conn-list">';
			
			//doawanie wartosci wybranej jako label
			$str.=$add;
			$str.='</div>';
		}
		else
			$str.= '</tr></table>';
		
		if( $is_hidden ) 	
			$str.= $this->hiddenField->generate(); 
			
		
		
		$str.="</div>";
	
		return $str; 
	}
	
	public function setCriteria( $criteria ){
		throw new ArrowException("[ArrowBindCtrl] Set criteria is not possible");
	}
	
	public function getCriteria(){
		if($this->criteria == null){
			$criteriaCont = $this->getChildren("ArrowCtrlCriteria");
			foreach( $criteriaCont as $criteria )
				$this->criteria[] = $criteria->getCriteria();
			if( count( $this->criteria ) == 1 ) $this->criteria = $this->criteria[0] ;	
		}
		return $this->criteria;
	}
	

}
?>
